#include "packets.h"
#include "macros.h"





cPacketBase::cPacketBase( int id ) {
	ASSERT( (id >= 0) && (id <= 255) )
	this->id = (unsigned char)id;
}

cPacketBase::cPacketBase() {
#if DEBUG
	this->id = INVALID_PACKET_ID;
#endif
}
	
cStream cPacketBase::getStream() {
	cStream ret;
	ret.writeByte(id);
	return ret;
}

unsigned int cPacketBase::length() {
	return 1;
}

bool cPacketBase::isValidID( int id ) {
	return id == PACKET_TERMINATOR_ID || id <= PACKET_LAST_ID;
}



// PACKET_MESSAGE

cMessagePacket::cMessagePacket(std::string msg) : cPacketBase(PACKET_MESSAGE_ID) {
	message = msg;
}

cStream cMessagePacket::getStream() {
	cStream ret = cPacketBase::getStream();
	ret.writeString(message);
	return ret;
}

unsigned int cMessagePacket::length() {
	return 1 + cStream::getStringLength(message);
}

// PACKET_DISCONNECT

cDisconnectPacket::cDisconnectPacket(std::string msg) : cPacketBase(PACKET_DISCONNECT_ID) {
	message = msg;
}

cStream cDisconnectPacket::getStream() {
	cStream ret = cPacketBase::getStream();
	ret.writeString(message);
	return ret;
}

unsigned int cDisconnectPacket::length() {
	return 1 + cStream::getStringLength(message);
}




// PACKET_LOGIN

cLoginResponsePacket::cLoginResponsePacket(std::string token) : cPacketBase(PACKET_LOGIN_ID) {
	this->salt = token;
	is_message = false;
}

cLoginResponsePacket::cLoginResponsePacket(bool success) : cPacketBase(PACKET_LOGIN_ID) {
	this->result = success ? 1 : 0;
	is_message = true;
}

cStream cLoginResponsePacket::getStream() {
	cStream ret = cPacketBase::getStream();
	ret.writeByte(is_message ? 1 : 0);
	if( is_message ) {
		ret.writeByte(result);
	}else{
		ret.writeString(salt);
	}
	return ret;
}

unsigned int cLoginResponsePacket::length() {
	return 1;
}


// PACKET_TERMINATOR
cTerminatorPacket::cTerminatorPacket() : cPacketBase( PACKET_TERMINATOR_ID ) { }


// PACKET_USERMNGLIST

cUserMngListPacket::cUserMngListPacket() : cPacketBase( PACKET_USERMNGLIST_ID ) { };
void cUserMngListPacket::addUser(unsigned int userid, std::string fullname, std::string username, std::string teacher, int groupid) {
	UserMngListUser_st usr;
	usr.userid = userid;
	usr.fullname = fullname;
	usr.username = username;
	usr.teacher = teacher;
	usr.groupid = groupid;
	users.push_back(usr);
}
cStream cUserMngListPacket::getStream() {
	cStream ret = cPacketBase::getStream();
	ret.writeInt(users.size());
	for(size_t i = 0; i < users.size(); i++) {
		ret.writeInt(users[i].userid);
		ret.writeString(users[i].username);
		ret.writeString(users[i].fullname);
		ret.writeString(users[i].teacher);
		ret.writeByte((char)users[i].groupid);
	}
	return ret;
}
unsigned int cUserMngListPacket::length() {
	return 1;
}




